package com.etrans.web.gps.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.Vector;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import com.etrans.web.gps.common.exception.BissinessException;

/**
 * 
 * <p>Title: StringUtils.java<／p>
 * <p>Description: <／p>
 * <p>Copyright: Copyright (c) 2007<／p>
 * <p>Company: E-trans<／p>
 * 
 * @author R.Lao
 * @date 2017年6月13日
 * @time 上午9:54:42
 * @version 1.0
 */
public class StringUtils {

	private static Object initLock = new Object();

	private static MessageDigest digest = null;

	private static final String commonWords[] = { "a", "and", "as", "at", "be", "do", "i", "if", "in", "is", "it", "so", "the", "to" };

	@SuppressWarnings("rawtypes")
	private static Map commonWordsMap = null;

	private static Random randGen = null;

	private static char numbersAndLetters[] = null;

	public StringUtils() {
	}

	/**
	 * 取当前日期或时间
	 * 
	 * @param sFormat
	 *            String -日期格式,参考java.text.SimpleDateFormat的格式要求,常用的日期格式有:
	 *            "yyyy-MM-dd HH:mm:ss"
	 * @return String
	 */
	public static String getToday(String sFormat) {
		SimpleDateFormat dateformatter = new SimpleDateFormat(sFormat);
		return dateformatter.format(new Date());
	}

	@SuppressWarnings("rawtypes")
	public static int getValue(Map values, String id, int defaultValue) {
		String value = getValue(values, id, "");
		if (value.equalsIgnoreCase(""))
			return defaultValue;
		try {
			int v = Integer.valueOf(value);
			return v;
		} catch (Exception ex) {
			return defaultValue;
		}

	}

	@SuppressWarnings("rawtypes")
	public static String getValue(Map values, String id, String defaultValue) {
		if (values == null)
			return defaultValue;
		Object value = values.get(id);
		if (value == null || value.equals(""))
			return defaultValue;
		return value.toString();
	}

	public static boolean isNULL(String str) {
		if ((str == null) || str.trim().equals(""))
			return true;
		return false;
	}

	/**
	 * 取日期字符串转换,日期格式为"hh:mm:ss"
	 * 
	 * @return String
	 */

	@SuppressWarnings("unused")
	public static long TimeToSecond(String strTime) {
		long sec = 0, count;
		String str[] = delimiterStrToArray(":", strTime);
		if (str.length > 0)
			sec = strTolong(str[0]) * 60 * 60;
		if (str.length > 1)
			sec += strTolong(str[1]) * 60;
		if (str.length > 2)
			sec += strTolong(str[2]);
		return sec;
	}

	public static long strTolong(String str) {
		long n = 0;
		try {
			n = Long.parseLong(str.trim());
		} catch (NumberFormatException e) {
		}
		return n;
	}

	/**
	 * 取日期函数,日期格式为"yyyy-MM-dd"
	 * 
	 * @return String
	 */

	public static String getToday() {
		SimpleDateFormat dateformatter = new SimpleDateFormat("yyyy-MM-dd");
		return dateformatter.format(new Date());
	}

	// 取当前的日期部分，时分秒不计，转换为秒数
	public static long getTodayInSecond() {
		java.util.Calendar c = new GregorianCalendar();
		int hour_flag = c.get(Calendar.HOUR_OF_DAY);
		if (hour_flag >= 12) {
			c.set(Calendar.HOUR, -12);
		} else {
			c.set(Calendar.HOUR, 0);
		}
		// c.set(Calendar.HOUR,-12);
		c.clear(Calendar.MINUTE);
		c.clear(Calendar.SECOND);
		return c.getTimeInMillis() / 1000;
	}

	public static long getNowInSecond() {
		java.util.Calendar c = new GregorianCalendar();
		return c.getTimeInMillis() / 1000;
	}

	/**
	 * 数据库日期时间转换为字符串
	 * 
	 * @param d
	 *            Timestamp -数据库得到的时间
	 * @param sFormat
	 *            String -转换格式参考java.text.SimpleDateFormat格式要求
	 * @return String
	 */

	public static String dateTimeToStr(Timestamp d, String sFormat) {
		if (d == null) {
			return "";
		} else {
			SimpleDateFormat dateformatter = new SimpleDateFormat(sFormat);
			String s = dateformatter.format(d);
			return s;
		}
	}

	/**
	 * 字符串转换为日期,字符串的格式必须是"yyyy-MM-dd HH:mm:ss"
	 * 
	 * @param s
	 *            String -输入字符串
	 * @return Date -转换后的日期
	 */
	public static Date strToDate(String s) {
		return toDate(s, null);
	}

	public static Date toDate(String strDate, Date defaultValue) {
		try {
			SimpleDateFormat datetimeformatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date = datetimeformatter.parse(strDate);
			return date;
		} catch (Exception e) {
			return defaultValue;
		}
	}

	public static Date toDay(String strDate, Date defaultValue) {
		try {
			SimpleDateFormat datetimeformatter = new SimpleDateFormat("yyyy-MM-dd");
			Date date = datetimeformatter.parse(strDate);
			return date;
		} catch (Exception e) {
			return defaultValue;
		}
	}

	public static String toString(Date date) {
		if (date == null)
			return "";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sdf.format(date);
	}

	/**
	 * 判断字符串中是否包含中文,该函数判断字符串中的字节是否有在0x80到0xFF间的字符.
	 * 
	 * @param s
	 *            String
	 * @return boolean
	 */

	public static boolean isChineseChar(String s) {
		boolean flag = false;
		if (s == null)
			return true;
		byte abyte0[] = s.getBytes();
		int i = 0;
		do {
			if (i >= abyte0.length)
				break;
			if (abyte0[i] < 0) {
				flag = true;
				break;
			}
			i++;
		} while (true);
		return flag;
	}

	/**
	 * 去除空字符串前后的空格,同时如果字符串为空,则返回""而不是null对象.
	 * 
	 * @param s
	 *            String -要处理的字符串
	 * @return String -处理后的结果字符串
	 */
	public static final String nullToEmptyOfStr(String s) {
		if (s != null)
			return s.trim();
		else
			return "";
	}

	/**
	 * 去除空字符串前后的空格,同时如果字符串为空,则返回缺省值而不是null对象.
	 * 
	 * @param s
	 *            String -要处理的字符串
	 * @param defValue
	 *            String-缺省值
	 * @return String
	 */

	public static final String nullToEmptyOfStr(String s, String defValue) {
		if (s != null)
			return s.trim();
		else
			return defValue;
	}

	public static byte[] DeleteZeroChar(byte[] dataBuf) {
		int count = getNonZeroCount(dataBuf);
		if (count == 0)
			return dataBuf;
		byte[] out = new byte[count];
		int index = 0;
		for (int i = 0; i < dataBuf.length; i++) {
			if (dataBuf[i] != 0) {
				out[index] = dataBuf[i];
				index++;
			}
		}
		return out;
	}

	private static int getNonZeroCount(byte[] dataBuf) {
		int count = 0;
		for (int i = 0; i < dataBuf.length; i++) {
			if (dataBuf[i] != 0)
				count++;
		}
		return count;
	}

	/**
	 * 如果对象存在返回对象的Class名称,如果对象不存在返回""
	 * 
	 * @param o
	 *            Object
	 * @return String
	 */

	public static final String nullToEmptyOfObject(Object o) {
		if (o != null)
			return o.toString();
		else
			return "";
	}

	/**
	 * 如果对象存在返回对象的Class名称,如果对象不存在返回缺省值
	 * 
	 * @param o
	 *            Object
	 * @param defValue
	 *            Object
	 * @return String
	 */

	public static final String nullToEmptyOfObject(Object o, Object defValue) {
		if (o != null)
			return o.toString();
		else
			return defValue.toString();
	}

	public static final boolean isDBNULL(String strValue) {
		if ((strValue == null) || (strValue.length() == 0) || (strValue.equalsIgnoreCase("null")))
			return true;
		return false;
	}

	/**
	 * 将字符串中的"\\"替换为"\\\\","\""替换为"\\\""
	 * 
	 * @param s
	 *            String
	 * @return String
	 */

	public static final String escapeErrorChar(String s) {
		String s1 = null;
		s1 = s;
		if (s1 == null) {
			return s1;
		} else {
			s1 = replace(s1, "\\", "\\\\");
			s1 = replace(s1, "\"", "\\\"");
			s1 = replace(s1, "\'", "\'");
			return s1;
		}
	}

	/**
	 * 判断字符串是否是一个数字"0-9"
	 * 
	 * @param s
	 *            String
	 * @return boolean
	 */
	@SuppressWarnings("unused")
	public static final boolean strIsDigital(String s) {
		boolean flag = false;
		boolean flag1 = true;
		char ac[] = s.toCharArray();
		int i = 0;
		if (i < ac.length && !Character.isDigit(ac[i]))
			flag1 = false;
		return flag1;
	}

	@SuppressWarnings("unused")
	public static final boolean checkIdCard(String s, String s1) {
		boolean flag = true;
		String s2 = "";
		String s3 = "";
		String s4 = "";
		String s5 = "";
		if (s.length() != 15 && s.length() != 18 || !isDate(s1))
			flag = false;
		else if (s.length() == 15) {
			if (!strIsDigital(s)) {
				flag = false;
			} else {
				String s6 = "19".concat(String.valueOf(String.valueOf(s.substring(6, 8))));
				String s8 = s.substring(8, 10);
				String s10 = s.substring(10, 12);
				String s12 = String.valueOf(String.valueOf((new StringBuffer(String.valueOf(String.valueOf(s6)))).append("-").append(s8).append("-").append(s10)));
				if (!s12.equals(s1))
					flag = false;
			}
		} else if (s.substring(17, 18).equals("X") || s.substring(17, 18).equals("x")) {
			if (!strIsDigital(s.substring(0, 18)))
				flag = false;
		} else if (!strIsDigital(s)) {
			flag = false;
		} else {
			String s7 = s.substring(6, 10);
			String s9 = s.substring(10, 12);
			String s11 = s.substring(12, 14);
			String s13 = String.valueOf(String.valueOf((new StringBuffer(String.valueOf(String.valueOf(s7)))).append("-").append(s9).append("-").append(s11)));
			if (!s13.equals(s1))
				flag = false;
		}
		return flag;
	}

	@SuppressWarnings("unused")
	public static boolean isDate(String s) {
		boolean flag = false;
		DateFormat dateformat = DateFormat.getDateInstance();
		if (s == null)
			flag = false;
		try {
			Date date = dateformat.parse(s);
			flag = true;
		} catch (Exception exception) {
			flag = false;
		}
		return flag;
	}

	public static String isInputError(int i, int j) {
		if ((i & j) > 0)
			return "Error";
		else
			return "True";
	}

	@SuppressWarnings({ "rawtypes", "unused", "unchecked" })
	public static Vector splite(String s, String s1) {
		Vector vector = new Vector();
		Object obj = null;
		Object obj1 = null;
		boolean flag = false;
		do {
			if (s.length() < 0)
				break;
			int i = s.indexOf(s1);
			if (i < 0) {
				vector.addElement(s);
				break;
			}
			String s2 = s.substring(0, i);
			vector.addElement(s2);
			s = s.substring(i + s1.length(), s.length());
		} while (true);
		return vector;
	}

	public static final String replace(String s, String s1, String s2) {
		if (s == null)
			return null;
		int i = 0;
		if ((i = s.indexOf(s1, i)) >= 0) {
			char ac[] = s.toCharArray();
			char ac1[] = s2.toCharArray();
			int j = s1.length();
			StringBuffer stringbuffer = new StringBuffer(ac.length);
			stringbuffer.append(ac, 0, i).append(ac1);
			i += j;
			int k;
			for (k = i; (i = s.indexOf(s1, i)) > 0; k = i) {
				stringbuffer.append(ac, k, i - k).append(ac1);
				i += j;
			}

			stringbuffer.append(ac, k, ac.length - k);
			return stringbuffer.toString();
		} else {
			return s;
		}
	}

	public static final String replaceIgnoreCase(String s, String s1, String s2) {
		if (s == null)
			return null;
		String s3 = s.toLowerCase();
		String s4 = s1.toLowerCase();
		int i = 0;
		if ((i = s3.indexOf(s4, i)) >= 0) {
			char ac[] = s.toCharArray();
			char ac1[] = s2.toCharArray();
			int j = s1.length();
			StringBuffer stringbuffer = new StringBuffer(ac.length);
			stringbuffer.append(ac, 0, i).append(ac1);
			i += j;
			int k;
			for (k = i; (i = s3.indexOf(s4, i)) > 0; k = i) {
				stringbuffer.append(ac, k, i - k).append(ac1);
				i += j;
			}

			stringbuffer.append(ac, k, ac.length - k);
			return stringbuffer.toString();
		} else {
			return s;
		}
	}

	public static final String replace(String s, String s1, String s2, int ai[]) {
		if (s == null)
			return null;
		int i = 0;
		if ((i = s.indexOf(s1, i)) >= 0) {
			int j = 0;
			j++;
			char ac[] = s.toCharArray();
			char ac1[] = s2.toCharArray();
			int k = s1.length();
			StringBuffer stringbuffer = new StringBuffer(ac.length);
			stringbuffer.append(ac, 0, i).append(ac1);
			i += k;
			int l;
			for (l = i; (i = s.indexOf(s1, i)) > 0; l = i) {
				j++;
				stringbuffer.append(ac, l, i - l).append(ac1);
				i += k;
			}

			stringbuffer.append(ac, l, ac.length - l);
			ai[0] = j;
			return stringbuffer.toString();
		} else {
			return s;
		}
	}

	public static final String formatInputStr(String s) {
		String s1 = s;
		s1 = nullToEmptyOfStr(s1);
		s1 = escapeHTMLTags(s1);
		return s1;
	}

	@SuppressWarnings("unused")
	public static final String escapeHTMLTags(String s) {
		if (s == null || s.length() == 0)
			return s;
		StringBuffer stringbuffer = new StringBuffer(s.length());
		byte byte0 = 32;
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if (c == '<') {
				stringbuffer.append("&lt;");
				continue;
			}
			if (c == '>')
				stringbuffer.append("&gt;");
			else
				stringbuffer.append(c);
		}

		return stringbuffer.toString();
	}

	public static final synchronized String hash(String s) {
		if (digest == null)
			try {
				digest = MessageDigest.getInstance("MD5");
			} catch (NoSuchAlgorithmException nosuchalgorithmexception) {
				System.err.println("Failed to load the MD5 MessageDigest. Jive will be unable to function normally.");
				nosuchalgorithmexception.printStackTrace();
			}
		digest.update(s.getBytes());
		return toHex(digest.digest());
	}

	public static final String toHex(byte abyte0[]) {
		StringBuffer stringbuffer = new StringBuffer(abyte0.length * 2);
		for (int i = 0; i < abyte0.length; i++) {
			if ((abyte0[i] & 0xff) < 16)
				stringbuffer.append("0");
			stringbuffer.append(Long.toString(abyte0[i] & 0xff, 16));
		}

		return stringbuffer.toString();
	}

	public static final String[] toLowerCaseWordArray(String s) {
		if (s == null || s.length() == 0)
			return new String[0];
		StringTokenizer stringtokenizer = new StringTokenizer(s, " ,\r\n.:/\\+");
		String as[] = new String[stringtokenizer.countTokens()];
		for (int i = 0; i < as.length; i++)
			as[i] = stringtokenizer.nextToken().toLowerCase();

		return as;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static final String[] removecommonWords(String as[]) {
		if (commonWordsMap == null)
			synchronized (initLock) {
				if (commonWordsMap == null) {
					commonWordsMap = new HashMap();
					for (int i = 0; i < commonWords.length; i++)
						commonWordsMap.put(commonWords[i], commonWords[i]);

				}
			}
		ArrayList arraylist = new ArrayList(as.length);
		for (int j = 0; j < as.length; j++)
			if (!commonWordsMap.containsKey(as[j]))
				arraylist.add(as[j]);

		return (String[]) arraylist.toArray(new String[arraylist.size()]);
	}

	public static final String randomString(int i) {
		if (i < 1)
			return null;
		if (randGen == null)
			synchronized (initLock) {
				if (randGen == null) {
					randGen = new Random();
					numbersAndLetters = "0123456789abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
				}
			}
		char ac[] = new char[i];
		for (int j = 0; j < ac.length; j++)
			ac[j] = numbersAndLetters[randGen.nextInt(71)];

		return new String(ac);
	}

	public static final String chopAtWord(String s, int i) {
		if (s == null)
			return s;
		char ac[] = s.toCharArray();
		int j = s.length();
		if (i < j)
			j = i;
		for (int k = 0; k < j - 1; k++) {
			if (ac[k] == '\r' && ac[k + 1] == '\n')
				return s.substring(0, k);
			if (ac[k] == '\n')
				return s.substring(0, k);
		}

		if (ac[j - 1] == '\n')
			return s.substring(0, j - 1);
		if (s.length() < i)
			return s;
		for (int l = i - 1; l > 0; l--)
			if (ac[l] == ' ')
				return s.substring(0, l).trim();

		return s.substring(0, i);
	}

	public static final String highlightWords(String s, String as[], String s1, String s2) {
		if (s == null || as == null || s1 == null || s2 == null)
			return null;
		for (int i = 0; i < as.length; i++) {
			String s3 = s.toLowerCase();
			char ac[] = s.toCharArray();
			String s4 = as[i].toLowerCase();
			int j = 0;
			if ((j = s3.indexOf(s4, j)) < 0)
				continue;
			int k = s4.length();
			StringBuffer stringbuffer = new StringBuffer(ac.length);
			boolean flag = false;
			char c = ' ';
			if (j - 1 > 0) {
				c = ac[j - 1];
				if (!Character.isLetter(c))
					flag = true;
			}
			boolean flag1 = false;
			char c1 = ' ';
			if (j + k < ac.length) {
				c1 = ac[j + k];
				if (!Character.isLetter(c1))
					flag1 = true;
			}
			if (flag && flag1 || j == 0 && flag1) {
				stringbuffer.append(ac, 0, j);
				if (flag && c == ' ')
					stringbuffer.append(c);
				stringbuffer.append(s1);
				stringbuffer.append(ac, j, k).append(s2);
				if (flag1 && c1 == ' ')
					stringbuffer.append(c1);
			} else {
				stringbuffer.append(ac, 0, j);
				stringbuffer.append(ac, j, k);
			}
			j += k;
			int l;
			for (l = j; (j = s3.indexOf(s4, j)) > 0; l = j) {
				boolean flag2 = false;
				char c2 = ac[j - 1];
				if (!Character.isLetter(c2))
					flag2 = true;
				boolean flag3 = false;
				if (j + k < ac.length) {
					c1 = ac[j + k];
					if (!Character.isLetter(c1))
						flag3 = true;
				}
				if (flag2 && flag3 || j + k == ac.length) {
					stringbuffer.append(ac, l, j - l);
					if (flag2 && c2 == ' ')
						stringbuffer.append(c2);
					stringbuffer.append(s1);
					stringbuffer.append(ac, j, k).append(s2);
					if (flag3 && c1 == ' ')
						stringbuffer.append(c1);
				} else {
					stringbuffer.append(ac, l, j - l);
					stringbuffer.append(ac, j, k);
				}
				j += k;
			}

			stringbuffer.append(ac, l, ac.length - l);
			s = stringbuffer.toString();
		}

		return s;
	}

	public static final String escapeForXML(String s) {
		if (s == null || s.length() == 0)
			return s;
		char ac[] = s.toCharArray();
		StringBuffer stringbuffer = new StringBuffer(ac.length);
		for (int i = 0; i < ac.length; i++) {
			char c = ac[i];
			if (c == '<') {
				stringbuffer.append("&lt;");
				continue;
			}
			if (c == '>') {
				stringbuffer.append("&gt;");
				continue;
			}
			if (c == '"') {
				stringbuffer.append("&quot;");
				continue;
			}
			if (c == '&') {
				stringbuffer.append("&amp;");
				continue;
			}
			if (c == '\n') {
				continue;
			} else
				stringbuffer.append(c);
		}

		return stringbuffer.toString();
	}

	public static final String unescapeFromXML(String s) {
		if (s == null)
			return "";
		s = replace(s, "&lt;", "<");
		s = replace(s, "&gt;", ">");
		s = replace(s, "&amp;", "&");
		return replace(s, "&quot;", "\"");
	}

	/**
	 * 
	 * @param s
	 *            String
	 * @param i
	 *            int
	 * @return String
	 */

	@SuppressWarnings({ "rawtypes", "unused" })
	public static final String formatTextArea(String s, int i) {
		if (s == null)
			return "";
		String s1 = s.trim();
		Vector vector = null;
		int j = i;
		s1 = String.valueOf(String.valueOf(s1)).concat("\n");
		vector = splite(s1, "\n");
		boolean flag = false;
		boolean flag1 = false;
		String s2 = "";
		String s4 = "";
		String s6 = "";
		char ac[] = s1.toCharArray();
		StringBuffer stringbuffer = new StringBuffer(ac.length);
		for (int k = 0; k < vector.size() - 1; k++) {
			String s5 = vector.elementAt(k).toString();
			s5 = replace(s5, "\r", "");
			if (s5.length() > j) {
				String s7 = s5;
				for (int l = 0; l < s5.length() / j; l++) {
					String s3 = String.valueOf(String.valueOf(s7.substring(0, j))).concat("\n");
					stringbuffer.append(s3.toCharArray(), 0, s3.toCharArray().length);
					s7 = s7.substring(j, s7.length());
				}

				stringbuffer.append(String.valueOf(String.valueOf(s7)).concat("\n").toCharArray(), 0, String.valueOf(String.valueOf(s7)).concat("\n").toCharArray().length);
			} else {
				stringbuffer.append(String.valueOf(String.valueOf(s5)).concat("\n").toCharArray(), 0, String.valueOf(String.valueOf(s5)).concat("\n").toCharArray().length);
			}
		}

		return stringbuffer.toString().trim();
	}

	/**
	 * 双精度浮点数转换成字符串,如果小数点后面位数过长,采用四舍五入.
	 * 
	 * @param value
	 *            double-要转换的浮点数
	 * @param precision
	 *            int -小数点后面保留的位数
	 * @return String -转换后的字符串
	 */
	public static String doubleToString(double value, int precision) {
		String val = Double.toString(value);
		if (val.indexOf(".") > 0 && val.substring(val.indexOf(".")).length() >= precision) {
			// 进行四舍五入计算
			double add = 0.5D;
			for (int i = 0; i < precision; i++)
				add /= 10;
			double resource = value + add;
			// 取小数点前的所有位数+小数点,及小数点后的前精度要求的位数
			String res = Double.toString(resource);
			String pre = res.substring(0, res.indexOf("."));
			String post = res.substring(res.indexOf("."), res.indexOf(".") + 1 + precision);
			val = String.valueOf(pre) + String.valueOf(post);
		}
		return val;
	}

	/**
	 * 将8859_1字符串转换为GB2312字符串
	 * 
	 * @param m_str
	 *            String
	 * @return String
	 */
	public static final String toChinese(String m_str) {
		String return_str = "";
		if (m_str == null)
			return "";
		try {
			byte m_bstr[] = m_str.getBytes("8859_1");
			return_str = new String(m_bstr, "GB2312");
		} catch (Exception e) {
			System.err.println("toChinese error caught: ".concat(String.valueOf(String.valueOf(e.getMessage()))));
		}
		return return_str;
	}

	/**
	 * 将8859_1字符串转换为GB2312字符串
	 * 
	 * @param m_str
	 *            String
	 * @return String
	 */

	public static final String toGB2312(String m_str) {
		return toChinese(m_str);
	}

	/**
	 * 将8859_1字符串转换为Big5字符串
	 * 
	 * @param m_str
	 *            String
	 * @return String
	 */
	public static final String toBig5(String m_str) {
		String return_str = "";
		try {
			byte m_bstr[] = m_str.getBytes("8859_1");
			return_str = new String(m_bstr, "Big5");
		} catch (Exception e) {
			System.err.println("toBig5 error caught: ".concat(String.valueOf(String.valueOf(e.getMessage()))));
		}
		return return_str;
	}

	/**
	 * 将GB2312字符串转换为8859_1字符串
	 * 
	 * @param m_str
	 *            String
	 * @return String
	 */
	public static final String toISO8859(String m_str) {
		String return_str = "";
		try {
			byte m_bstr[] = m_str.getBytes("GB2312");
			return_str = new String(m_bstr, "8859_1");
		} catch (Exception e) {
			System.err.println("toChinese error caught: ".concat(String.valueOf(String.valueOf(e.getMessage()))));
		}
		return return_str;
	}

	/**
	 * 将多个字符串根据分隔符,拼成一个大字符串,如:<br>
	 * 如果arrayToDelimiterStr(",",str)其中str数组有"111","222","333"将返回"111,222,333"
	 * 
	 * @param delimiter
	 *            String -分隔符
	 * @param str
	 *            String[] -字符串数组
	 * @return String -拼成的大字符串
	 */

	public static String arrayToDelimiterStr(String delimiter, String[] str) {
		StringBuffer buf = new StringBuffer("");
		int i = 0;
		for (i = 0; i < str.length; i++) {
			buf.append(str[i]).append(delimiter);
		}
		if (i > 0)
			buf.delete(buf.length() - delimiter.length(), buf.length());
		return buf.toString();
	}

	/**
	 * 将具有分隔符的字符串,分隔成字符串数组,如:<br>
	 * delimiterStrToArray(",","111,222,333")将得到具有"111","222","333"的字符串数组
	 * 
	 * @param delimiter
	 *            String
	 * @param str
	 *            String
	 * @return String[]
	 */
	public static String[] toArray(String delimiter, String str) {
		StringTokenizer st = new StringTokenizer(str, delimiter);// 以/分隔，
		String[] buf = new String[st.countTokens()];
		int i = 0;
		while (st.hasMoreTokens())
			buf[i++] = st.nextToken();
		return buf;
	}

	/**
	 * 将具有分隔符的字符串,分隔成字符串数组,如:<br>
	 * delimiterStrToArray(",","111,222,333")将得到具有"111","222","333"的字符串数组
	 * 
	 * @param delimiter
	 *            String
	 * @param str
	 *            String
	 * @return String[]
	 */
	public static String[] delimiterStrToArray(String delimiter, String str) {
		StringTokenizer st = new StringTokenizer(str, delimiter);// 以/分隔，
		String[] buf = new String[st.countTokens()];
		int i = 0;
		while (st.hasMoreTokens())
			buf[i++] = st.nextToken();
		return buf;
	}

	/**
	 * 将字符串转换为Map结构,字符串必须用主分隔符和次分隔符来分开,举例如下:<br>
	 * delimiterStrToMap("Conn=oracleDB,USR=reltec,PWD=Marconi",",","=");<br>
	 * 该函数的返回Hashtable将有3个Key和Value对,Key分别是"Conn","USR","PWD",<br>
	 * 而Value分别是"oracleDB","reltec","Marconi"<br>
	 * 该函数的主要目的是对配置文件的配置信息进行拆分.<br>
	 * 
	 * @param str
	 *            String -要转换的字符串
	 * @param delimiterMain
	 *            String -字符串间的主分隔符
	 * @param delimiterSub
	 *            String -字符串间的次分隔符
	 * @return Hashtable
	 */
	@SuppressWarnings({ "rawtypes", "unused", "unchecked" })
	public static Hashtable delimiterStrToMap(String str, String delimiterMain, String delimiterSub) {
		if (isNULL(str))
			return new Hashtable();

		String[] strArray = delimiterStrToArray(delimiterMain, str);
		String[] strItem;
		Hashtable hsb = new Hashtable();
		for (int i = 0; i < strArray.length; i++) {
			String strs = strArray[i];
			int index = strs.indexOf(delimiterSub);
			if (index > 0) {
				String key = strs.substring(0, index);
				String value = strs.substring(index + 1);
				hsb.put(key, value);

			}
		}
		return hsb;
	}

	/**
	 * 将字符串转换为Map结构,字符串必须用主分隔符和次分隔符来分开,举例如下:<br>
	 * delimiterStrToMap("Conn=oracleDB,USR=reltec,PWD=Marconi",",","=");<br>
	 * 该函数的返回Hashtable将有3个Key和Value对,Key分别是"Conn","USR","PWD",<br>
	 * 而Value分别是"oracleDB","reltec","Marconi"<br>
	 * 该函数的主要目的是对配置文件的配置信息进行拆分.<br>
	 * 
	 * @param str
	 *            String -要转换的字符串
	 * @param delimiterMain
	 *            String -字符串间的主分隔符
	 * @param delimiterSub
	 *            String -字符串间的次分隔符
	 * @return Hashtable
	 */
	@SuppressWarnings({ "rawtypes", "unused", "unchecked" })
	public static Map toMap(String str, String delimiterMain, String delimiterSub) {
		if (isNULL(str))
			return new Hashtable();

		String[] strArray = delimiterStrToArray(delimiterMain, str);
		String[] strItem;
		Hashtable hsb = new Hashtable();
		for (int i = 0; i < strArray.length; i++) {
			String substr = strArray[i];
			int index = substr.indexOf(delimiterSub);
			if (index > 0) {
				String key = substr.substring(0, index);
				if (substr.length() > (index + 1)) {
					String value = substr.substring(index + 1);
					hsb.put(key, value);
				}
			}
		}
		return hsb;
	}

	/**
	 * 和arrayToDelimiterStr的功能相同,只是分隔符固定为"/"
	 * 
	 * @param csv
	 *            String -输入字符串
	 * @return String[]
	 * @deprecated
	 */

	public static String[] csvToArray(String csv) {
		return delimiterStrToArray("/", csv);
	}

	/**
	 * 和arrayToDelimiterStr函数的功能相同
	 * 
	 * @param csv
	 *            String -输入字符串
	 * @param separator
	 *            String -分隔符
	 * @return String[]
	 * @deprecated
	 */

	public static String[] csvToArray(String csv, String separator) {
		return delimiterStrToArray(csv, separator);
	}

	/**
	 * 该函数对字符串中有关HTML的特殊字符进行替换,如:<br>
	 * "<"替换为"&lt"<br>
	 * "'"替换为"&#039"<br>
	 * """替换为"&#034"<br>
	 * "\n"替换为"<br/>
	 * "等
	 * 
	 * @param in
	 *            String -输入字符串
	 * @return String -替换后的字符串
	 */
	public static String toHTMLString(String in) {
		StringBuffer out = new StringBuffer();
		for (int i = 0; in != null && i < in.length(); i++) {
			char c = in.charAt(i);
			if (c == '\'')
				out.append("&#039;");
			else if (c == '\"')
				out.append("&#034;");
			else if (c == '<')
				out.append("&lt;");
			else if (c == '>')
				out.append("&gt;");
			else if (c == '&')
				out.append("&amp;");
			else if (c == ' ')
				out.append("&nbsp;");
			else if (c == '\n')
				out.append("<br/>");
			else
				out.append(c);
		}
		return out.toString();
	}

	/**
	 * 该函数对字符串中有关XML的特殊字符进行替换,如:<br>
	 * "<"替换为"&lt"<br>
	 * ">"替换为"&gt"<br>
	 * "'"替换为"&apos;"<br>
	 * """替换为"&quot;"<br>
	 * "&"替换为"&amp;"等
	 * 
	 * @param in
	 *            String -输入字符串
	 * @return String -替换后的字符串
	 */
	public static String toXMLString(String in) {
		if (in == null)
			return "";
		StringBuffer out = new StringBuffer();

		String from = "<>&\'\"";
		String[] to = new String[from.length()];
		to[0] = "&lt;";
		to[1] = "&gt;";
		to[2] = "&amp;";
		to[3] = "&apos;";
		to[4] = "&quot;";
		for (int i = 0; in != null && i < in.length(); i++) {
			char c = in.charAt(i);
			int pos;
			pos = from.indexOf(c);
			if (pos == -1) {
				out.append(c);
			} else
				out.append(to[pos]);
		}
		return out.toString();
	}

	/**
	 * 该函数在特殊字符" \' 前面加上\
	 * 
	 * @param in
	 *            String -输入字符串
	 * @return String -替换后的字符串
	 */

	public static final String appendUnCanPrint(String in) {
		StringBuffer out = new StringBuffer();
		char One;
		char a = '"'; // 0x22
		char b = 0x5C; // \
		char c = 0x27; // '
		for (int i = 0; i < in.length(); i++) {
			One = in.charAt(i);
			if (One == a || One == b || One == c) {
				out.append(b);
			}
			out.append(One);
		}
		return out.toString();
	}

	/**
	 * 截取指定长度的字符串
	 * 
	 * @param in
	 *            String -输入字符串 *
	 * @param in
	 *            String - 指定长度
	 * @return String -指定长度的字符串
	 */

	public static String substring(String in, int length) {
		if (in == null)
			return "";
		if (in.length() < length)
			return in;
		return in.substring(0, length);
	}

	/**
	 * 按字节数截取字符串长度,但不能出现半个汉字的情况
	 * 
	 * @param source
	 *            要截取的字符串
	 * @length 要截取的长度
	 * @return 返回截取后的字符串
	 * @author Benjamin
	 */
	public static String substringB(String source, int lengthB) throws Exception {
		String returnStr = null;
		try {
			// 如果要截取长度大于字符串的字节数,则返回原字符串
			if (lengthB > source.getBytes().length) {
				return source;
				// length = source.getBytes().length;
			} else {
				int len = lengthB;
				if (lengthB > source.length())
					len = source.length();
				for (int i = len; i > 0; i--) {
					String substr = source.substring(0, i);
					if (lengthB >= substr.getBytes().length) {
						returnStr = substr;
						break;
					}

				}
			}
		} catch (Exception e) {
			System.out.println("function substringB error : " + e.getMessage());
			throw e;
		}
		return returnStr;
	}

	public static String substringToWeb(String source, int lengthB) throws Exception {
		StringBuffer strbuffer = new StringBuffer();
		try {
			if (source != null) {
				if (source.equals(""))
					strbuffer.append("&nbsp;");
				else if (source.getBytes().length > lengthB) {

					// 截取指定长度-2个字节(因为截取后加上的省略符号 "..." 约占2个字节宽)
					strbuffer.append("<span title='" + source + "'>");
					strbuffer.append(substringB(source, lengthB - 2));
					strbuffer.append("...</span>");
				} else {
					strbuffer.append(source);
				}
			} else
				strbuffer.append("&nbsp;");

		} catch (Exception e) {
			System.out.println("function substringToWeb error : " + e.getMessage());
			throw e;
		}
		return strbuffer.toString();
	}

	public static final String XML_PREFIX = "<?xml version=\"1.0\" encoding=\"GB2312\"?>";

	@SuppressWarnings("rawtypes")
	public static String toXMLResult(Map values) {
		return toXML(values, "UTF-8");
	}

	@SuppressWarnings("rawtypes")
	public static String toXML(Map values, String encoder) {
		if (values == null)
			return "";
		StringBuffer buf = new StringBuffer();
		buf.append("<?xml version=\"1.0\" encoding=\"" + encoder + "\"?>\r\n");
		buf.append("<root>\r\n");
		Object[] keys = values.keySet().toArray();
		for (int i = 0; i < keys.length; i++) {
			Object key = keys[i];
			Object value = values.get(keys[i]);
			buf.append("<").append(key).append(">");
			if (value != null)
				buf.append(toXMLString(value.toString()));
			buf.append("</").append(key).append(">\r\n");
		}
		buf.append("</root>\r\n");
		return buf.toString();
	}
 
 
 

	public static Map<String, String> toMap(String xml, String charset) throws BissinessException {
		if (xml == null)
			return null;
		DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance();
		Map<String, String> values = new Hashtable<String, String>();
		try {
			DocumentBuilder domBuilder = domfac.newDocumentBuilder();
			InputStream is = new ByteArrayInputStream(xml.getBytes(charset));
			org.w3c.dom.Document doc = domBuilder.parse(is);
			org.w3c.dom.Element root = doc.getDocumentElement();
			org.w3c.dom.NodeList nodes = root.getChildNodes();
			for (int i = 0; i < nodes.getLength(); i++) {
				org.w3c.dom.Node n = nodes.item(i);
				if (n instanceof org.w3c.dom.Element) {
					org.w3c.dom.Element e = (org.w3c.dom.Element) n;
					String key = e.getNodeName();
					String value = e.getNodeValue();
					if (StringUtils.isNULL(key) || value == null)
						continue;
					values.put(key, value);
				}
			}
		} catch (Exception e) {
			throw new BissinessException("转换Document失败,xml=" + xml + e.getMessage() + "错误是" + e.getMessage(), e);
		}
		return values;

	}
 

	@SuppressWarnings({ "rawtypes" })
	public static String toString(Map map, String delimiterMain, String delimiterSub) {
		if (map == null)
			return "";
		StringBuffer sb = new StringBuffer();
		Iterator ir = map.keySet().iterator();
		while (ir.hasNext()) {
			Object key = ir.next();
			sb.append(key + delimiterSub + map.get(key) + delimiterMain);
		}
		return sb.toString();
	}

	public static boolean simpleWildcardMatch(String pattern, String str) {
		return wildcardMatch(pattern, str, "*");
	}

	public static boolean wildcardMatch(String pattern, String str, String wildcard) {
		if (isNULL(pattern) || isNULL(str)) {
			return false;
		}
		final boolean startWith = pattern.startsWith(wildcard);
		final boolean endWith = pattern.endsWith(wildcard);
		String[] array = toArray(wildcard, pattern);
		int currentIndex = -1;
		int lastIndex = -1;
		switch (array.length) {
		case 0:
			return true;
		case 1:
			currentIndex = str.indexOf(array[0]);
			if (startWith && endWith) {
				return currentIndex >= 0;
			}
			if (startWith) {
				return currentIndex + array[0].length() == str.length();
			}
			if (endWith) {
				return currentIndex == 0;
			}
			return str.equals(pattern);
		default:
			for (String part : array) {
				currentIndex = str.indexOf(part);
				if (currentIndex > lastIndex) {
					lastIndex = currentIndex;
					continue;
				}
				return false;
			}
			return true;
		}
	}

	public static void main(String[] args) {
		String strNULL = null;
		if ((strNULL == null) || (strNULL.length() == 0))
			System.out.println("NULL String");

		String str = "DB=ORACLE,URL=jdbc:oracle:thin:@199.3.8.136:1521:oraCSRM,USER===ccatslbr===,PWD=marconi";
		System.out.print(StringUtils.toXML(delimiterStrToMap(str, ",", "="), "UTF-8"));
	}

	public static byte[] unzip(byte[] bytes) throws IOException {
		ByteArrayInputStream in = new ByteArrayInputStream(bytes);
		return unzip(in);
	}

	public static byte[] unzip(InputStream in) throws IOException {
		// Open the compressed stream
		GZIPInputStream gin = new GZIPInputStream(in);

		ByteArrayOutputStream out = new ByteArrayOutputStream();

		// Transfer bytes from the compressed stream to the output stream
		byte[] buf = new byte[1024];
		int len;
		while ((len = gin.read(buf)) > 0) {
			out.write(buf, 0, len);
		}

		// Close the file and stream
		gin.close();
		out.close();
		return out.toByteArray();
	}

	public static byte[] zip(InputStream in) throws IOException {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		GZIPOutputStream gop = new GZIPOutputStream(out);
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = in.read(buffer)) != -1) {
			gop.write(buffer, 0, len);
		}
		gop.finish(); //这个在写入arrayOutputStream时一定要有，否则不能完全写入  
		gop.close();
		return out.toByteArray();
	}

	public static byte[] zip(byte[] bytes) throws IOException {
		ByteArrayInputStream in = new ByteArrayInputStream(bytes);
		return zip(in);
	}
	
	/**
	 * 判断是否为空
	 * 
	 * @param value
	 * @return
	 */
	public static boolean isEmpty(String value){
		  if(value == null || value.isEmpty()) {
			  return true;
		  }else{
			  return false;
		  }
	}
	
	 public static String subZeroAndDot(String s){   
    	if(s != null && !"".equals(s)){
    		if(s.indexOf(".") > 0){   
    			s = s.replaceAll("0+?$", "");//去掉多余的0   
    			s = s.replaceAll("[.]$", "");//如最后一位是.则去掉   
    		}   
    		return s;   
    	}else{
    		return "";
    	}
    }  
}
